use serialport::{SerialPort, SerialPortType, DataBits, FlowControl, Parity, StopBits};
use std::io::{self, Write};
use std::time::Duration;

fn main() -> io::Result<()> {
    // 配置串口参数
    let settings = serialport::SerialPortSettings {
        baud_rate: 9600,
        data_bits: DataBits::Eight,
        flow_control: FlowControl::None,
        parity: Parity::None,
        stop_bits: StopBits::One,
        timeout: Duration::from_millis(10),
    };

    // 打开串口
    let port_name = "COM3"; // 根据实际情况修改串口名称
    let mut port = serialport::open_with_settings(&port_name, &settings)?;

    // 发送数据
    let msg = "Hello, Serial Port!\n";
    port.write_all(msg.as_bytes())?;
    println!("Sent: {}", msg);

    // 读取响应
    let mut buffer = [0; 255];
    match port.read(&mut buffer) {
        Ok(t) => {
            let received = String::from_utf8_lossy(&buffer[..t]);
            println!("Received: {}", received);
        }
        Err(e) => {
            eprintln!("Error reading from serial port: {}", e);
        }
    }

    Ok(())
}